<?php

namespace App\Observers;

use App\Wiki;
use App\WikiRevision;
use Arr;
use Auth;

class WikiObserver
{
    public function created(Wiki $wiki)
    {

        $wiki->refreshCache();

    }

    public function saved(Wiki $wiki)
    {
        $request = request();
        if ($request->body || $request->category) {
            // 创建一个版本
            $revision = $wiki->revisions()->create([
                'type' => $request->type,
                'user_id' => Auth::id(),
            ]);
        }
        if ($content = $request->body) {
            $data = ['body' => $content];
            $revision->content()->updateOrCreate(['contentable_id' => $revision->id], $data);
            $revision->loadMissing('content');
        }

        if ($requestCategory = $request->category) {
            // 处理分类
            $requestCategory = is_array($requestCategory) ?: explode(',', $requestCategory);

            $revision->categories()->sync($requestCategory);
            $revision->load('categories');
            // 更新
            foreach ($revision->categories as $category) {
                $category->refreshCache();
            }
        }
    }
}
